<script setup>
import Emoji from "@/components/emoji/emoji.vue";
import {create_say, say_comment, say_like, list_say} from "@/apis/v1/say/say.js";
import {useUserStore} from "@/store/user.js";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {ChatDotRound, Location, MoreFilled, Timer} from "@element-plus/icons-vue";

const router = useRouter();
const BASE_IMG_URL = ref(import.meta.env.VITE_APP_IMG_API);
const userStore = useUserStore();
const title = ref("");
const sayList = ref([]);
const operateBox = ref();
const lastIndex = ref(null);
const commentIndex = ref(null);
const lastEditRange = ref(null);
const isComment = ref(false);
const showEmoji = ref(false);
const comment = ref({
  content: "",
});
const getSayList = () => {
  list_say().then(res => {
    if (res.code === 200) {
      sayList.value = res.result;
    }
  });
};
const sayLike = (say) => {
  say_like(say.id).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
    } else {
      say.userLikeList.push({
        id: userStore.user.id,
        nickname: userStore.user.nickname,
      });
      say.isLike = true;
      ElMessage.success(res.message);
    }
  });
};
const canLike = (say) => {
  say_like(say.id).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
    } else {
      let index = null;
      for (let i = 0; i < say.userLikeList.length; i++) {
        let id = say.userLikeList[i].id;
        if (userStore.user.id === id) {
          index = i;
          break;
        }
      }
      if (index != null) {
        say.userLikeList.splice(index, 1);
      }
      say.isLike = false;
      ElMessage.success(res.message);
    }
  });
};
const sayComment = (item, index) => {
  title.value = "评论说说";
  commentIndex.value = index;
  isComment.value = true;
  comment.value.say_id = item.id;
  comment.value.user_id = userStore.user.id;
  console.log(comment.value);
};
const sayCommentOK = () => {
  let el = document.getElementById("sayComment");
  if (!el.innerHTML) {
    ElMessage.warning('请输入评论内容');
  } else {
    comment.value.content = el.innerHTML;
    say_comment(comment.value).then(res => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
      } else {
        ElMessage.success(res.message);
        const content = {
          nickname: userStore.user.nickname,
          content: el.innerHTML,
        };
        sayList.value[commentIndex.value].userCommentList.push(content);
        el.innerHTML = "";
        comment.value.content = "";
      }
    });
  }
  isComment.value = false;
};
const saySend = () => {
  title.value = "发布说说";
  isComment.value = true;
};
const saySendOK = () => {
  let el = document.getElementById("sayComment");
  if (!el.innerHTML) {
    ElMessage.warning('请输入发布内容');
  } else {
    comment.value.content = el.innerHTML;
    create_say({content: comment.value.content}).then(res => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
      } else {
        ElMessage.success(res.message);
        router.go(0);
        el.innerHTML = "";
        comment.value.content = "";
      }
    });
  }
  isComment.value = false;
};
const onInput = (e) => {
  let selection = window.getSelection();
  lastEditRange.value = selection.getRangeAt(0);
};
const onHandleShowOperate = (index) => {
  if (lastIndex.value !== null && lastIndex.value !== index) {
    operateBox.value[lastIndex.value].style.display = "none";
  }
  if (lastIndex.value === index) {
    if (operateBox.value[index].style.display === "block") {
      operateBox.value[index].style.display = "none";
    } else {
      operateBox.value[index].style.display = "block";
    }
  } else {
    operateBox.value[index].style.display = "block";
  }
  lastIndex.value = index;
};
const onHandleChooseEmoji = (value) => {
  console.log(value);
  // 创建一个img标签（表情）
  let img = document.createElement('img');
  img.src = value.url;
  img.style.verticalAlign = 'middle';
  img.style.marginLeft = "2px";
  img.style.marginRight = "2px";
  img.style.maxHeight = value.maxHeight;
  img.style.height = value.height;
  img.style.width = value.width;
  let edit = document.getElementById("sayComment");
  edit.focus()
  let selection = window.getSelection()
  // 如果存在最后的光标对象
  if (lastEditRange.value) {
    // 选区对象清除所有光标
    selection.removeAllRanges();
    // 并添加最后记录的光标，以还原之前的状态
    selection.addRange(lastEditRange.value);
    // 获取到最后选择的位置
    var range = selection.getRangeAt(0);
    // 在此位置插入表情图
    range.insertNode(img)
    // false，表示将Range对象所代表的区域的起点移动到终点处
    range.collapse(false)
    // 记录最后的位置
    lastEditRange.value = selection.getRangeAt(0);
  } else {
    // 将表情添加到可编辑的div中，作为可编辑div的子节点
    edit.appendChild(img)
    // 使用选取对象，选取可编辑div中的所有子节点
    selection.selectAllChildren(edit)
    // 合并到最后面，即实现了添加一个表情后，把光标移到最后面
    selection.collapseToEnd()
  }
  showEmoji.value = false;
};
onMounted(() => {
  getSayList();
});
</script>

<template>
  <div class="content">
    <div class="say-item" v-for="(item, index) in sayList" :key="item.id">
      <div class="avatar">
        <el-avatar :src="BASE_IMG_URL + item.avatar" alt=""></el-avatar>
      </div>
      <div class="right-box">
        <div class="nickname center">
          <span style="margin-right: 3px">{{ item.nickname }}</span>
          <el-tooltip class="item" effect="dark" :content="item.user === 1 ? '博主' : '用户' " placement="right">
            <img class="svg-icon" src="@/icons/svg/bozhu.svg" alt="">
          </el-tooltip>
        </div>
        <p style="margin-top: 10px;" v-html="item.content"></p>
        <div class="say-bottom">
          <div class="address">
            <a class="center">
              <el-icon>
                <Location/>
              </el-icon>
              {{ item.address ? item.address : '暂无发布地址' }}
            </a>
          </div>
          <div class="operate">
            <div class="time center">
              <el-icon>
                <Timer/>
              </el-icon>
              {{ item.create_datetime }}
            </div>
            <div class="more-btn" @click="onHandleShowOperate(index)">
              <el-icon>
                <MoreFilled/>
              </el-icon>
            </div>
            <div class="operate-box" ref="operateBox">
              <span class="like" v-if="!item.isLike" @click="sayLike(item)">
                <i style="margin-right: 5px" class="iconfont icon-dianzan"></i> 赞
              </span>
              <span class="like" v-else @click="canLike(item)">
                <i style="margin-right: 5px" class="iconfont icon-quxiaodianzan"></i> 取消
              </span>
              <div class="fgx">|</div>
              <span class="center" @click="sayComment(item, index)">
                <el-icon style="margin-right: 5px"><ChatDotRound/></el-icon>评论
              </span>
              <div class="fgx">|</div>
              <span @click="saySend">发布说说</span>
            </div>
          </div>
          <div class="interaction">
            <div v-if="item.userLikeList.length" style="display: flex;"
                 :class="item.userLikeList.length ? 'like-container is_border':'like-container'">
              <div v-for="(user, user_index) in item.userLikeList" :key="user_index">
                <i class="iconfont icon-dianzan"></i>
                <span>{{ user.nickname }}</span>
              </div>
            </div>
            <div class="comment">
              <div class="comment-item" v-for="(comment, comment_index) in item.userCommentList" :key="comment_index">
                <div style="padding-bottom: 5px">
                  <span class="username">{{ comment.nickname }}：</span>
                  <span class="content point" v-html="comment.content"></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog v-model="isComment" :title="title">
      <div class="comment-input" ref="commentInputBox">
        <div>
          <div class="comment-textarea" id="sayComment" contenteditable="true"
               data-placeholder="请输入内容：" @input="onInput" ref="textareaRef"></div>
          <span class="point" @click="showEmoji = !showEmoji">
                    <i class="iconfont icon-biaoqing"></i>
                  </span>
          <a v-if="title === '评论说说'" class="send-btn point" @click="sayCommentOK">发送</a>
          <a v-if="title === '发布说说'" class="send-btn point" @click="saySendOK">发布</a>
        </div>
        <div class="emoji-wrapper" v-if="showEmoji">
          <Emoji @chooseEmoji="onHandleChooseEmoji"></Emoji>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.content {
  margin-bottom: 50px;
  width: 1200px;
  color: var(--text-color);

  .say-item {
    position: relative;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 5px;
    background-color: var(--background2);
    overflow: hidden;
    display: flex;

    .avatar {
      margin-right: 10px;

      /deep/ img {
        vertical-align: top;
      }
    }

    .right-box {
      width: 100%;
      display: flex;
      flex-direction: column;

      .center {
        display: flex;
        align-items: center;
      }

      .nickname {
        color: var(--theme-color);
      }

      .say-bottom {
        position: relative;
        margin-top: 20px;

        .address {
          color: #5597bd;
          font-size: 14px;
          margin-bottom: 10px;
        }

        .operate {
          position: relative;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .time {
            font-size: 14px;
          }

          .more-btn {
            cursor: pointer;
            margin-right: 10px;
            padding: 5px 5px 0;
            background-color: var(--background2);
          }

          .operate-box {
            position: absolute;
            right: 50px;
            bottom: -5px;
            padding: 8px;
            border-radius: 5px;
            background-color: #4b5153;
            display: none;

            &:after {
              content: '';
              position: absolute;
              right: -15px;
              bottom: 10px;
              width: 0;
              height: 0;
              border-width: 8px;
              border-style: solid;
              border-color: transparent transparent transparent #4b5153;
            }

            span {
              cursor: pointer;
              position: relative;
              padding: 0 10px;
              color: #fff;
              float: left;

              &:hover {
                color: var(--theme-color);
              }
            }

            .fgx {
              float: left;
              width: 2px;
              height: 100%;
              color: #373D40;
            }
          }
        }
      }

      .interaction {
        margin-top: 15px;
        border-radius: 5px;
        background-color: var(--background2);

        .is_border {
          border-bottom: 1px dashed rgb(126, 120, 120);
        }

        .like-container {
          padding: 8px 0 8px 10px;

          div {
            color: #576b95;
            font-size: 14px;
            margin-right: 5px;
            display: flex;
            align-items: center;

            span {
              margin-left: 2px;
            }
          }
        }

        .comment {
          .comment-item {
            margin: 5px 0;
            padding-left: 10px;

            &:first-child {
              margin-top: 10px;
            }

            .username {
              color: #5597bd;
            }
          }
        }
      }
    }
  }

  .comment-input {
    position: relative;
    min-height: 100px;
    margin-left: 10px;
    border-radius: 5px;
    border: 1px solid #67C23A;
    background-color: var(--background-color);

    .comment-textarea {
      outline: none;
      min-height: 100px;
      padding-left: 10px;
      padding-top: 5px;

      &:empty:before {
        color: #666;
        content: attr(data-placeholder);
      }
    }

    i {
      font-size: 1.3rem;
      position: absolute;
      right: 80px;
      bottom: 20px;
    }

    .send-btn {
      position: absolute;
      right: 20px;
      bottom: 15px;
      padding: 5px 8px 5px 8px;
      border-radius: 5px;
      background-color: #67C23A;
      color: #fff;
      display: inline-block;
    }
  }
}
</style>